//
//  CFUtility.m
//  CFFinanceProject
//
//  Created by chunfeng on 2018/4/9.
//  Copyright © 2018年 xiaowen. All rights reserved.
//

#import "CFUtility.h"
//#import "NSString+ToDate.h" checkoutTwoTimeStringVaryMoreThenTenMin方法需要倒入



/**
 获取IP地址需要导入
 */
#import <ifaddrs.h>
#import <arpa/inet.h>

#import <CommonCrypto/CommonDigest.h> //md5需导入文件

@implementation CFUtility


/**
 *提示框,Tim添加
 */
+ (void)showTips:(NSString *)tips
{
    if (!tips)return;
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:DEF_KEYWINDOW animated:YES];
    hud.mode=MBProgressHUDModeText;
    hud.detailsLabel.text=tips;
    hud.detailsLabel.font = [UIFont systemFontOfSize:15];
    hud.removeFromSuperViewOnHide=YES;
    hud.minSize=CGSizeMake(140, 25);
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:1.2];
}


+ (void)setExtraCellLineHidde:(UITableView *)tableView tabHeader:(BOOL) header tabFooter:(BOOL) footer
{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    if (!header) {
        [tableView setTableHeaderView:view];
    }
    if (!footer) {
        [tableView setTableFooterView:view];
    }
}

//MD5加密
+(NSString *) md5: (NSString *) inPutText
{
    if (!inPutText) {
        return inPutText;
    }
    const char *cStr = [inPutText UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    NSString *md5Result = [NSString stringWithFormat:
                           @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           result[0], result[1], result[2], result[3],
                           result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11],
                           result[12], result[13], result[14], result[15]
                           ];
    return md5Result;
}
//判断非空
+(NSString *)NSNULLString:(NSString *)string{
    if( [string isEqualToString:@""]||[string length]==0||[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){
        return string;
    }
    return nil;
}

//限制特殊字符不能输入@
+(int) XZInputText:(NSString *) stringText{
    NSCharacterSet *nameCharacters = [NSCharacterSet
                                      characterSetWithCharactersInString:@"`~!@#$%^&*()+=|{}':;',\\[\\].<>?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？"];
    NSRange userNameRange = [stringText rangeOfCharacterFromSet:nameCharacters];
    
    if (userNameRange.location != NSNotFound) {
        return 0;//包含特殊字符
    }else{
        return 1;
    }
    return 1;
    
    //用法
    
    /**
     if ([self XZInputText:_userAddress.text]==0) {
     MessageSHAREShow(@"不能输入特殊字符");
     return false;
     }
     */
}
//判断密码
+(BOOL)CheckInput:(NSString *)text{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:text];
    return isMatch;
    
}

//检测手机号
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    if(mobileNum.length == 0 || mobileNum == nil || mobileNum.length < 11) return NO;
    
    NSString *Regex = @"^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|147)\\d{8}$";//以前用的
    NSPredicate *phone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [phone evaluateWithObject:mobileNum];
}
//获取IP地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}


//!!!!: 风火轮加载信息
/**
 *  风火轮加载信息
 *
 *  @param _targetView 对象
 *  @param _msg        提示信息
 */
+ (void)showMBProgress:(UIView *)_targetView message:(NSString *)_msg {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:_targetView];
        progressHUD.mode = MBProgressHUDModeIndeterminate;
        [progressHUD showAnimated:YES];
        progressHUD.label.text = _msg;
        [_targetView addSubview:progressHUD];
    });
    
}

+ (void)hideMBProgress:(UIView*)_targetView{
    
    [MBProgressHUD hideHUDForView:_targetView animated:YES];
}

/**
 *  将时间戳转换为指定格式时时间
 *
 *  @param strTimestamp  传入的时间戳
 *  @param strDateFormat 时间的格式
 *
 *  @return 返回的时间
 */
+ (NSString *)getTimeWithTimestamp:(NSString *)strTimestamp WithDateFormat:(NSString *)strDateFormat
{
    
    /**
     
     时间戳转换
     
     */
    if ([strTimestamp isEqualToString:@"0"]||[strTimestamp length]==0)
    {
        return @"";
    }
    
    long long time;
    if (strTimestamp.length == 10) {
        time = [strTimestamp longLongValue];
    }
    if (strTimestamp.length == 13){
        time = [strTimestamp longLongValue]/1000;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:strDateFormat];
    NSString *strTime = [formatter stringFromDate:date];
    return strTime;
    
    
    
    /**
     
     - returns:  时间转换yyyy-MM-dd
     
     重点 服务器返回的是一个yyyy-MM-dd HH:mm:ss格式  需要先获取一个格式一样的本地时间,才可以进行正常转换
     
     */
    
    //
    //    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    //
    //    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //
    //    NSString *dateString=[NSString stringWithFormat:@"%@", strTimestamp];
    //
    //    NSDate *date =[dateFormat dateFromString:dateString];
    //
    //    NSDateFormatter* dateFormat2 = [[NSDateFormatter alloc] init];
    //
    //    [dateFormat2 setDateFormat:strDateFormat];
    //
    //    NSString *publishtimeStr = [dateFormat2 stringFromDate:date ];
    //
    //    return  publishtimeStr;
}


/**
 *  根据目标字符判断该字符是否存在值
 *
 *  @param string 目标字符
 *
 *  @return yes->存在
 */
+ (BOOL)checkoutStringIsExistWithTargetString:(NSString *)string {
    if (string == nil) {
        return NO;
    }
    
    if ([string isEqual:[NSNull null]]) {
        return NO;
    }
    
    if ([string isEqualToString:@""]) {
        return NO;
    }
    
    if ([string isEqualToString:@"nil"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"null"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"Nil"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"NULL"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(nil)"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(null)"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(Nil)"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(NULL)"]) {
        return NO;
    }
    
    return YES;
}



//+ (BOOL)checkoutTwoTimeStringVaryMoreThenTenMin:(NSString *)firstTime secondTime:(NSString *)secondTime {
//    NSTimeInterval back = 10*60;
//    NSDate *secondDate = [secondTime toAllInfoDate];
//    NSDate *resultData = [NSDate dateWithTimeInterval:back sinceDate:secondDate];
//    NSTimeInterval firstTimeInterval = [firstTime toTimeInterval1970];
//    NSTimeInterval secondTimeInterval = [resultData timeIntervalSince1970];
//    if (firstTimeInterval >= secondTimeInterval) {
//        return YES;
//    } else {
//        return NO;
//    }
//
//}


+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar high = [substring characterAtIndex: 0];
                                
                                // Surrogate pair (U+1D000-1F9FF)
                                if (0xD800 <= high && high <= 0xDBFF) {
                                    const unichar low = [substring characterAtIndex: 1];
                                    const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                                    
                                    if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
                                        returnValue = YES;
                                    }
                                    
                                    // Not surrogate pair (U+2100-27BF)
                                } else {
                                    if (0x2100 <= high && high <= 0x27BF){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

+ (NSDate *)getInternetDate{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (NSString *)dencode:(NSString *)base64String
{
    //NSData *base64data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    return string;
}

+ (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    return baseString;
}

+ (NSString *)replaceUnicode:(NSString *)unicodeStr {
    if (![CFUtility checkoutStringIsExistWithTargetString:unicodeStr]) {
        return @"";
    }
    
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    if ([returnStr isNullOrEmpty]) {
        return unicodeStr;
    }else{
        return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
    }
}

+(NSString *)encodeToUnicode:(NSString *)string{
    NSUInteger length = [string length];
    NSMutableString *s = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++)
    {
        unichar _char = [string characterAtIndex:i];
        //判断是否为英文和数字
        //        if (_char <= '9' && _char >= '0')
        //        {
        //            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
        //        }
        //        else if(_char >= 'a' && _char <= 'z')
        //        {
        //            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
        //        }
        //        else if(_char >= 'A' && _char <= 'Z')
        //        {
        //            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
        //        }
        //        else
        //        {
        [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
        //       }
    }
    return s;
}

+ (UIViewController *) getVC:(NSString *)vcId Storyboard:(NSString *)Storyboard {
    return [[UIStoryboard storyboardWithName:Storyboard bundle:nil] instantiateViewControllerWithIdentifier:vcId];
}


+ (void)animationAlert:(UIView *)view
{
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = 0.4;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.0f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [view.layer addAnimation:popAnimation forKey:nil];
    
}

+(NSString *) connectUrl:(NSMutableDictionary *)params url:(NSString *) urlLink{
    // 初始化参数变量
    NSString *str = @"?";
    // 快速遍历参数数组
    for(id key in params) {
        NSLog(@"key :%@  value :%@", key, [params objectForKey:key]);
        str = [str stringByAppendingString:key];
        str = [str stringByAppendingString:@"="];
        str = [str stringByAppendingString:[params objectForKey:key]];
        str = [str stringByAppendingString:@"&"];
    }
    // 处理多余的&以及返回含参url
    if (str.length > 1) {
        // 去掉末尾的&
        str = [str substringToIndex:str.length - 1];
        // 返回含参url
        return [urlLink stringByAppendingString:str];
    }
    return Nil;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSString *)stringWithDictionary:(NSDictionary *)dic{
    
    if (dic == nil) {
        return nil;
    }
     NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    if(err) {
        NSLog(@"dic转string失败：%@",err);
        return nil;
    }
    NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
    
}

+(NSString *)stringWithArray:(NSArray *)arr{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr
                                                       options:kNilOptions
                                                         error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    return jsonString;
}

+ (NSArray *)stringToJSON:(NSString *)jsonStr {
    if (jsonStr) {
        id tmp = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        if (tmp) {
            if ([tmp isKindOfClass:[NSArray class]]) {
                
                return tmp;
                
            } else if([tmp isKindOfClass:[NSString class]]
                      || [tmp isKindOfClass:[NSDictionary class]]) {
                
                return [NSArray arrayWithObject:tmp];
                
            } else {
                return nil;
            }
        } else {
            return nil;
        }
        
    } else {
        return nil;
    }
}


+ (void)setAttributeStringForPriceLabel:(UILabel *)label text:(NSString *)text
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString
                                              alloc] initWithString:text];
    NSUInteger length = [text length];
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.firstLineHeadIndent = 10;
    style.headIndent = 10;   //设置与头部的距离
    style.tailIndent = -10; //设置与尾部的距离
//    style.alignment = NSTextAlignmentCenter;//靠哪显示
    [attrString addAttribute:NSParagraphStyleAttributeName value:style
                       range:NSMakeRange(0, length)];
    label.attributedText = attrString;
}


+ (NSString *)getStringReplaceByMessageContent:(NSString *)content{

    // 读取并加载对照表
    if (!content) {
        return @"";
    }else {

        NSString *path = [[NSBundle mainBundle] pathForResource:@"CFemotionReplace" ofType:@"plist"];
        
        NSDictionary  *emojiImages = [NSDictionary dictionaryWithContentsOfFile:path];
        
        //比对结果
        NSString *regexString = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5\\em_0-9]+\\]";
        
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:nil];
        
        NSRange totalRange = NSMakeRange(0, [content length]);
        
        NSArray *matches = [regex matchesInString:content options:0 range:totalRange];
        
        NSMutableSet * macthSet = [[NSMutableSet alloc] init];
        for (int i = 0; i<matches.count; i++) {
            NSTextCheckingResult *match = [matches objectAtIndex:i];
            NSRange matchRange = [match range];
            NSString *tagString = [content substringWithRange:matchRange];
            
            [macthSet addObject:tagString];
        }
        NSEnumerator * enumerator = [macthSet objectEnumerator];
        NSString * str;
       // NSString * urlToot = @"http://file.xtgj8.com";
        // 遍历替换字符串
        while (str = [enumerator nextObject]) {
            
            NSString *imageName  = [emojiImages objectForKey:str] ;
//           NSMutableString *imageName = [[NSMutableString alloc] initWithString:[emojiImages objectForKey:str]];
//            [imageName insertString:urlToot atIndex:10];
            content = [content stringByReplacingOccurrencesOfString:str withString:imageName];
            
        }
       
        return content;
    }
}

//
+ (NSArray *)filterImage:(NSString *)html
{
    NSMutableArray *resultArray = [NSMutableArray array];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
    
    for (NSTextCheckingResult *item in result) {
        NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
        
        NSArray *tmpArray = nil;
        if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
            tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
        } else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
            tmpArray = [imgHtml componentsSeparatedByString:@"src="];
        }
        
        if (tmpArray.count >= 2) {
            NSString *src = tmpArray[1];
            
            NSUInteger loc = [src rangeOfString:@"\""].location;
            if (loc != NSNotFound) {
                src = [src substringToIndex:loc];
                [resultArray addObject:src];
            }
        }
    }
    
    return resultArray;
}

//+(UIImage *)getauthimage{
//    NSString * url = [NSString stringWithFormat:@"%@%@?deviceId=%@",DEF_INTERFACE_WEBVIEWSERVICE,DEF_URL_GETAUTHIMAGE,DEF_DEVICEUUID];
//    NSString * newUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:newUrl]]];
//    return img;
//}


//限制只能11位

+ (void)textLengthLimitbits:(UITextField *)textfield{

//    [[textfield rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
//        if (x.length>=11) {
//            textfield.text = [textfield.text substringToIndex:11];
//        }
//    }];
}

//限制输入框的输入位

+ (void)textLengthLimitbitsNum:(UITextField *)textfield num:(NSUInteger)num{
    
//    [[textfield rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
//        if (x.length>=num) {
//            textfield.text = [textfield.text substringToIndex:num];
//        }
//    }];
}


+ (NSString *)toJson:(id)data {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:1 error:&error];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (NSString *)getThreeDigitRandomNumber{
    int a = arc4random() % 100;
    return  [NSString stringWithFormat:@"%03d", a];
}

+ (NSString *)getRandomStringWithNum:(NSInteger)num{
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < num; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}

+(NSString *)notRounding:(double)price afterPoint:(int)position{
    NSNumber *number = @(price);
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.roundingMode = NSNumberFormatterRoundFloor;
    formatter.maximumFractionDigits = position;
    NSString * pointStr = [NSString stringWithFormat:@"%%.%df",position];
    return [NSString stringWithFormat:pointStr,[[formatter stringFromNumber:number] doubleValue]];
    
}


/**
 *  判断两个浮点数是否整除
 *
 *  @param firstNumber  第一个浮点数(被除数)
 *  @param secondNumber 第二个浮点数(除数,不能为0)
 *
 *  @return 返回值可判定是否整除
 */
+ (BOOL)judgeDivisibleWithFirstNumber:(CGFloat)firstNumber andSecondNumber:(CGFloat)secondNumber {
    // 默认记录为整除
    BOOL isDivisible = YES;
    
    if (secondNumber == 0) {
        return NO;
    }
    
    CGFloat result = firstNumber / secondNumber;
    NSString * resultStr = [NSString stringWithFormat:@"%f", result];
    NSRange range = [resultStr rangeOfString:@"."];
    NSString * subStr = [resultStr substringFromIndex:range.location + 1];
    
    for (NSInteger index = 0; index < subStr.length; index ++) {
        unichar ch = [subStr characterAtIndex:index];
        
        // 后面的字符中只要有一个不为0，就可判定不能整除，跳出循环
        if ('0' != ch) {
            //            NSLog(@"不能整除");
            isDivisible = NO;
            break;
        }
    }
    
    // NSLog(@"可以整除");
    return isDivisible;
}



/**
 获取之前之后的日期

 @param day 间隔
 @return 日期
 */
+ (NSString *)getDateLater:(NSInteger) day {
    //    NSInteger day = 7; //前后的天数
    
    NSDate*nowDate = [NSDate date];
    
    NSDate* theDate;
    
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    
    //之后的天数
    
    theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*day ];
    
    //之前的天数
    
    //    theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*day ];
    
    //实例化一个NSDateFormatter对象
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    //用[NSDate date]可以获取系统当前时间
    
    NSString * currentDateStr = [dateFormatter stringFromDate:theDate];
    
    return currentDateStr;
    
    NSLog(@"%@",currentDateStr);
}

+ (UIImage*)gradientImageWithBounds:(CGRect)bounds andColors:(NSArray*)colors andGradientType:(int)gradientType{
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(bounds.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start;
    CGPoint end;
    
    switch (gradientType) {
        case 0:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(0.0, bounds.size.height);
            break;
        case 1:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(bounds.size.width, 0.0);
            break;
    }
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

+ (NSString *)sha1:(NSString *)input{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

+ (void)addLine:(UILabel *)marketLab{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:marketLab.text];
    
    NSRange strRange = {0,[str length]};
    
    [str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:1] range:strRange];
    
    [marketLab setAttributedText:str];
}

+ (CGFloat)setTextWidthWithString:(NSString*)text height:(CGFloat)height fontSize:(NSInteger)fontSize {
    if (![text isNullOrEmpty]){
        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
        CGRect frame = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading  attributes:dict context:nil];
        return frame.size.width;
    }else{
        return 0;
    }
}


+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
    CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"
                                  keysAndValues:kCIInputImageKey, inputImage,
                        @"inputRadius", @(blur),nil];
    
    CIImage *outputImage = filter.outputImage;
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef outImage = [context createCGImage:outputImage fromRect:[inputImage extent]];
    return [UIImage imageWithCGImage:outImage];
}


@end
